package thread;
//不安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"华子").start();
        new Thread(buyTicket,"华华").start();
        new Thread(buyTicket,"张旭").start();
    }
}
class BuyTicket implements Runnable{
    //票
    private int ticketNums =10;
    //外部停止方式
    boolean flag =true;
    @Override
    public void run() {
        //买票
        while (flag) {
            buy();
            //模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private synchronized void buy(){
        //判断是否有票
        if (ticketNums<=0) {
            flag=false;
            return;
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}